<template>
  <view class="container">
    <view class="header">
      <text class="title">🌡 智能设备实时报警中心</text>
    </view>

    <!-- 连接状态 -->
    <view v-if="!connected" class="status">
      🔌 正在连接服务器...
    </view>

    <!-- 无报警 -->
    <view v-else-if="alerts.length === 0" class="status ok">
      ✅ 当前环境正常，无报警
    </view>

    <!-- 报警列表 -->
    <scroll-view v-else class="alert-box" scroll-y>
      <view v-for="(item, index) in alerts" :key="index" class="alert-item">
        <text class="alert-icon">⚠️</text>
        <text class="alert-text">{{ item }}</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { connectWebSocket, closeWebSocket } from '@/utils/websocket.js';

// 响应式变量
const connected = ref(false);
const alerts = ref([]);
const message = ref('');

// 消息处理函数
function handleMessage(data) {
  // 纯文本解析
  if (data === 'OK') {
    alerts.value = [];
    message.value = 'OK';
  } else if (!data.includes('连接成功')) {
    alerts.value = data.split('；').filter(v => v.trim() !== '');
    message.value = data;
    uni.vibrateLong(); // 报警震动提示
  }
}

let ws = null;
onMounted(() => {
  ws = connectWebSocket('ws://localhost:8080/ws/monitor', (data) => {
    console.log('📩 推送内容：', data);
    connected.value = true; // 一旦收到数据，标记连接成功
    handleMessage(data);
  });

  ws.onOpen(() => {
    connected.value = true;
    console.log('✅ WebSocket 已连接');
  });

  ws.onClose(() => {
    connected.value = false;
    console.log('❌ WebSocket 已关闭');
  });
});

onUnmounted(() => {
  closeWebSocket();
});
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx;
  background-color: #f7f7f7;
  min-height: 100vh;
}

.header {
  margin-bottom: 40rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.status {
  font-size: 28rpx;
  color: #888;
  margin-bottom: 20rpx;
}

.status.ok {
  color: #22bb33;
}

.alert-box {
  width: 90%;
  background: #fff;
  border-radius: 20rpx;
  padding: 20rpx;
  box-shadow:
}
</style>